package com.example.smartvillage.cunmin;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import com.example.smartvillage.MainViewModel;
import com.example.smartvillage.R;
import com.example.smartvillage.onenet.MyOneNetApi;
import com.google.android.material.bottomsheet.BottomSheetDialogFragment;
import com.google.android.material.button.MaterialButton;
import com.google.android.material.textview.MaterialTextView;
import com.google.gson.JsonArray;

import java.util.Objects;

public class DoorSecurityFragment extends BottomSheetDialogFragment {

    private static final String TAG = "门与安防";

    MainViewModel model;
    MyOneNetApi myOneNetApi;

    MaterialButton btn_open, btn_close;
    MaterialTextView tv_door,tv_visitor;

    public DoorSecurityFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        model = new ViewModelProvider(requireActivity()).get(MainViewModel.class);
        myOneNetApi = Objects.requireNonNull(model.getMyOneNetApi().getValue());

        //每次进入更新数据
        boolean[] newDoorStates = new boolean[2];
        String dataStreamIds = "门开关 ,门外状态 ";
        myOneNetApi.getDataStreams(dataStreamIds, response -> {
            if (response.body() != null && response.body().get("errno").getAsInt() == 0) {
                JsonArray obj = response.body().get("data").getAsJsonArray();
                newDoorStates[0] = (obj.get(0).getAsJsonObject().get("current_value").getAsInt() == 1);
                newDoorStates[1] = (obj.get(1).getAsJsonObject().get("current_value").getAsInt() == 1);
                Log.d(TAG, "获取的门与安防状态，门开关：" + newDoorStates[0] + "，门外状态：" + newDoorStates[1]);
                model.setDoorStates(newDoorStates);
            }
        });
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view =  inflater.inflate(R.layout.fragment_door_security, container, false);

        btn_open = view.findViewById(R.id.door_security_open);
        btn_close = view.findViewById(R.id.door_security_close);
        tv_door = view.findViewById(R.id.door_security_door);
        tv_visitor = view.findViewById(R.id.door_security_visitor);

        btn_open.setOnClickListener(btnOpenClickListener);
        btn_close.setOnClickListener(btnCloseClickListener);

        model.getDoorStates().observe(this, doorStatesObserver);

        return view;
    }

    //上升按钮监听
    View.OnClickListener btnOpenClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            boolean[] states = model.getDoorStates().getValue();
            //在线命令
            myOneNetApi.sendCommand("door:1", response -> {
                if (response.body() != null && response.body().get("errno").getAsInt() == 0) {
                    Toast.makeText(getContext(), "成功创建命令", Toast.LENGTH_SHORT).show();

                    //更新ViewModel中的数据
                    states[0] = true;
                    model.setDoorStates(states);
                }
                else if (response.body().get("errno").getAsInt() == 10) {
                    Toast.makeText(getContext(), "设备不在线", Toast.LENGTH_SHORT).show();
                }
            });
        }
    };
    //下降按钮监听
    View.OnClickListener btnCloseClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            boolean[] states = model.getDoorStates().getValue();
            //在线命令
            myOneNetApi.sendCommand("door:0", response -> {
                if (response.body() != null && response.body().get("errno").getAsInt() == 0) {
                    Toast.makeText(getContext(), "成功创建命令", Toast.LENGTH_SHORT).show();

                    //更新ViewModel中的数据
                    states[0] = false;
                    model.setDoorStates(states);
                }
                else if (response.body().get("errno").getAsInt() == 10) {
                    Toast.makeText(getContext(), "设备不在线", Toast.LENGTH_SHORT).show();
                }
            });
        }
    };

    Observer<boolean[]> doorStatesObserver = new Observer<boolean[]>() {
        @Override
        public void onChanged(boolean[] booleans) {
            Log.d(TAG, "ViewModel中门与安防状态改变，门开关：" + booleans[0] + "，门外状态：" + booleans[1]);
            tv_door.setText(booleans[0]?"门已打开":"门已关闭");
            tv_door.setTextColor(getResources().getColor(booleans[0]?R.color.warning:R.color.colorPrimary));
            tv_visitor.setText(booleans[1]?"门外有人":"门外无人");
            tv_visitor.setTextColor(getResources().getColor(booleans[1]?R.color.warning:R.color.darker_gray));
        }
    };
}